/*
 * Copyright Notice ====================================================
 * This file contains proprietary information of Hewlett-Packard Co.
 * Copying or reproduction without prior written approval is prohibited.
 * Copyright (c) 2013 All rights reserved. =============================
 */

package com.hp.ecs.xqa.util;

import java.io.Closeable;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;


public class IoUtil {
	public static void close(Closeable res) {
		if (res != null) {
			try {
				res.close();
			} catch (IOException e) {
				// Just quietly close the resource.
			}
		}
	}

	public static void write(byte[] bytes, File f) {
		FileOutputStream outStream = null;
		try {
			if (!f.exists()) {
				f.createNewFile();
			}
			outStream = new FileOutputStream(f);
			outStream.write(bytes);
		} catch (Throwable e) {
			throw new RuntimeException(e);
		} finally {
			if (outStream != null)
				try {
					outStream.close();
				} catch (Exception e) {
					// Ignore
				}
		}
	}

	private static byte[] trim(byte[] src, int len) {
		byte[] dest = new byte[len];
		for (int i = 0; i < len; i++) {
			dest[i] = src[i];
		}
		return dest;
	}

	public static void copy(File src, File dest) {
		try {
			write(read(new FileInputStream(src)), dest);
		} catch (FileNotFoundException e) {
			throw new IllegalArgumentException("No found file:" + src.getName(), e);
		}
	}

	public static byte[] read(InputStream in) {
		List list = new LinkedList();
		int size = 0;
		try {
			int len;
			for (byte[] bytes = new byte[1024]; (len = in.read(bytes)) > 0;) {
				size += len;
				list.add(trim(bytes, len));
			}
			ByteBuffer buffer = ByteBuffer.allocate(size);
			for (Iterator it = list.iterator(); it.hasNext();) {
				buffer.put((byte[])it.next());
			}
			return buffer.array();
		} catch (IOException e) {
			throw new RuntimeException(e);
		} finally {
			try {
				in.close();
			} catch (Exception e) {
				// Ignore
			}
		}
	}

	public static byte[] read(InputStream in, int count) {
		List<Byte> list = new ArrayList();
		try {
			int b;
			while ((b = in.read()) != -1) {
				list.add((byte)b);
			}
			byte[] bytes = new byte[list.size()];
			int i = 0;
			for (Byte bt : list) {
				bytes[i++] = bt;
			}
			return bytes;
		} catch (IOException e) {
			throw new RuntimeException(e);
		} finally {
			try {
				in.close();
			} catch (Exception e) {
				// Ignore
			}
		}

	}
}
